/*  
 * Video Game Network Library
 * http://gamenetlib.codeplex.com/
 * 
 * Copyright (c) 2011 Joe Hegarty
 *  
 * This source code is subject to the terms of the Microsoft Public License (Ms-PL). 
 *  
 * Redistribution and use in source and binary forms, with or without modification, 
 * is permitted provided that redistributions of the source code retain the above 
 * copyright notices and this file header. 
 * 
 * For details, see <http://www.opensource.org/licenses/ms-pl.html>. 
 *  
 * All other rights reserved. 
 *
 */  

#include <string>
#include <conio.h>
#include "stdafx.h"
#include "NetLib.hpp"
#include "socket/NetSocketWrapper.hpp"
#include "socket/NetSocketAddress.hpp"


int _tmain(int argc, _TCHAR* argv[])
{
	NNetLib::u16 localPort = 4566;
	NNetLib::u16 remotePort = 4567;

	if(argc > 2)
	{
		localPort = _wtoi(argv[1]);
		remotePort = _wtoi(argv[2]);
	}

	std::cout << "##########################" << std::endl; 
	std::cout << "Local Port: " << localPort << std::endl; 
	std::cout << "Remote Port: " << remotePort << std::endl; 
	std::cout << "##########################" << std::endl << std::endl;  

	// Initialise our network library, including Winsock
	if(NNetLib::StartNetLib())
	{
		std::cout << "Network library initialised..." << std::endl;
		NNetLib::CSocketWrapper socket;
		// Create and bind our socket
		if(socket.Create(localPort))
		{
			// Set the socket to non-blocking for this example
			socket.SetBlocking(false);
			std::cout << "Socket created..." << std::endl;
			NNetLib::u32 remoteAddress = NNetLib::CSocketAddress::CreateAddress(127, 0, 0, 1);
			NNetLib::CSocketAddress remoteSocket(remoteAddress, remotePort);

			while(true)
			{
				// Send some data
				const std::string dataToSend = "Welcome to the world of tomorrow!";
				if(socket.Send(remoteSocket, dataToSend.c_str(), dataToSend.length()))
				{
					std::cout << "Sent " << dataToSend.length() << " bytes of data to port " << remoteSocket.GetPort() <<  std::endl;
				}

				// Receive data
				bool moreData = true;
				do
				{
					char dataOut[1024];
					NNetLib::CSocketAddress receiverSocket;
					NNetLib::u32 receiveSize = 0;

					moreData = socket.Receive(receiverSocket, dataOut, receiveSize, sizeof(dataOut));

					if(moreData)
					{
						std::cout << "Received " << receiveSize << " bytes of data from port " << receiverSocket.GetPort() << std::endl;
					}

				} while (moreData);

				// Dirty, but let's sleep in this example
				::Sleep(1000);
			}

			// Close the socket
			socket.Close();
			
		}
	}

	// Shutdown the network library, including winsock
	NNetLib::ShutdownNetLib();

	return 0;
}

